package my.jwds.p167;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class TwoSum {

    public static void main(String[] args) {
        TwoSum o = new TwoSum();
        int [] res = o.twoSum(new int[]{2,7,11,15},9);
        System.out.println(Arrays.toString(res));
        res = o.twoSum_twoPointer(new int[]{2,7,11,11},9);
        System.out.println(Arrays.toString(res));
    }

    public int[] twoSum(int[] numbers, int target) {
        HashMap<Integer,int[]> h = new HashMap<>();
        for (int i = 0; i < numbers.length; i++) {
            int[] val = h.get(numbers[i]);
            if (val == null){
                val = new int[2];
                val[0] = i+1;
            }else{
                val[1] = i+1;
            }
            h.put(numbers[i],val);
        }
        for (Map.Entry<Integer, int[]> entry : h.entrySet()) {
            int[] val = h.get(target - entry.getKey());
            if (val != null){
                if (val[1] != 0)return val;
                if (entry.getValue()[0] > val[0])return new int[]{val[0],entry.getValue()[0]};
                return new int[]{entry.getValue()[0],val[0]};
            }
        }
        return null;
    }
    public int[] twoSum_twoPointer(int[] numbers, int target) {
        int l=0,r=numbers.length-1;
        while(true){
            int val = numbers[l]+numbers[r];
            if (val>target){
                r--;
            }else if (val<target){
                l++;
            }else{
                return new int[]{l+1,r+1};
            }
        }
    }
}



